package com.xukehong.demo.util;

import com.github.binarywang.utils.qrcode.BufferedImageLuminanceSource;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.common.HybridBinarizer;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xkh
 **/
@Slf4j
public class QrCodeUtil {

    public static String decoderQrCode(File file) throws Exception {
        try {
            BufferedImage image = ImageIO.read(file);
            return decodeQrCode(image);
        } catch (IOException e) {
            log.error("二维码数据读取失败", e);
            throw new Exception("二维码解析失败");
        }
    }

    public static String decodeQrCode(InputStream inputStream) throws Exception {
        try {
            BufferedImage image = ImageIO.read(inputStream);
            return decodeQrCode(image);
        } catch (IOException e) {
            log.error("二维码数据读取失败", e);
            throw new Exception("二维码解析失败");
        }
    }

    private static String decodeQrCode(BufferedImage bufferedImage) throws Exception {
        try {
            BufferedImageLuminanceSource bufferedImageLuminanceSource = new BufferedImageLuminanceSource(bufferedImage);
            HybridBinarizer hybridBinarizer = new HybridBinarizer(bufferedImageLuminanceSource);
            BinaryBitmap binaryBitmap = new BinaryBitmap(hybridBinarizer);
            Map<DecodeHintType, Object> hints = new HashMap<>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            return new MultiFormatReader().decode(binaryBitmap, hints).getText();
        } catch (NotFoundException e) {
            log.error("二维码解析失败", e);
            throw new Exception("二维码解析失败");
        }
    }


    public static InputStream getImageStream(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            System.out.println("获取网络图片出现异常，图片路径为：" + url);
            e.printStackTrace();
        }
        return null;
    }
}
